package com.servlet;


import java.sql.ResultSet;
import com.database.SQLConnection;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Insect
 */
public class LoginValidatorServlet extends HttpServlet {
   int roleId=0;
private static String className = LoginValidatorServlet.class.getName();
private static Logger classLogger = Logger.getLogger(className);

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

        String userName= (String)request.getParameter("username");
        String password= (String)request.getParameter("password");
        boolean isValidLogin=checkLogin(userName,password);
        if(isValidLogin){
            request.setAttribute("username", userName);
            if(roleId == 1)
                getServletContext().getRequestDispatcher("/admin/home.jsp").forward(request, response);
            else
                getServletContext().getRequestDispatcher("/user/home.jsp").forward(request, response);
        }
        else
            getServletContext().getRequestDispatcher("/common/loginerror.jsp").forward(request, response);
    }

    private boolean checkLogin(String userName,String password) {
        
        int counter = 0;

        if(null != userName && null != password){
            Connection con = (Connection)new SQLConnection().getMySQLConnection();
            try {
                PreparedStatement pstmt = con.prepareStatement("Select * from user where username like ? and password like ?");
                pstmt.setString(1, userName);
                pstmt.setString(2, password);
                ResultSet rs=pstmt.executeQuery();
                while(rs.next()){
                    counter++;
                    roleId=rs.getInt("roleId");
                }
            } catch (SQLException ex) {
                classLogger.log(Level.SEVERE, "Exception in DB call: While checking login", ex);
            }
        }
        if(counter < 1)
            return false;
        if(counter > 1)
            return false;
        return true;
    }

}
